/*
 * Copyright (c) 2010-2013 Ruben Chakhmakhchyan. All rights reserved.
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Eclipse Public License
 * Version 1.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/EPL-1.0 and read it before using this file.
 */

#include "bmp_encoder.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>


// saves dib to bmp
size_t BmpEncoder::encode( byte_t** dest, byte_t* source, size_t sourceLength )
{
    size_t destLen = 0;

    size_t size = sizeof( BITMAPFILEHEADER ) + sourceLength;
    size_t offBits = 0;

    PBITMAPINFOHEADER pbih = ( PBITMAPINFOHEADER ) source;
    unsigned int colors = 0;

    switch ( pbih->biBitCount )
    {
    case 8: colors = sizeof( RGBQUAD ) << 8; break;
    case 1: colors = sizeof( RGBQUAD ) << 1; break;
    }

    BITMAPFILEHEADER bfh = { 0 };
    bfh.bfType = 0x4D42;
    bfh.bfSize = size;
    bfh.bfOffBits = sizeof( BITMAPFILEHEADER ) + sizeof( BITMAPINFOHEADER ) + colors;

    byte_t* destData = ( byte_t* ) malloc( size );

    memcpy( destData, &bfh, sizeof( BITMAPFILEHEADER ) );
    memcpy( destData + sizeof( BITMAPFILEHEADER ), source, sourceLength );

    *dest = destData;
    destLen = size;

    return destLen;
}
